<!--
 * @Description: 
 * @Author: spicylemon
 * @Date: 2022-02-23 16:06:09
 * @LastEditors: spicylemon
 * @LastEditTime: 2022-03-07 08:09:06
-->
<template>
  <div class="init">
    <footer class="action-box">
      <div class="action">
        <div class="action-img" @click="good" :class="isLike(article_data)">
          <i class="iconfont icon-dianzan foot-icon"></i>
          <span class="foot-num">{{ article_data.likes }}</span>
        </div>
      </div>
      <div class="action">
        <div class="action-img action-img-color" @click="comment">
          <i class="iconfont icon-pinglun foot-icon"></i>
          <span class="foot-num">{{ article_data.comments }}</span>
        </div>
      </div>
      <div class="action">
        <div
          class="action-img"
          @click="collection"
          :class="isCollect(article_data)"
        >
          <i class="iconfont icon-shoucang foot-icon"></i>
          <span class="foot-num">{{ article_data.collections }}</span>
        </div>
      </div>
    </footer>
    <div class="header">
      <span class="header-back"
        ><i class="iconfont icon-fanhui" @click="router.push('/')"></i
      ></span>
      <span class="herder-middle">正文</span>
      <button v-if="deleteBtnDis" @click="toDeleteArticle" class="deletBtnDis">
        删除文章
      </button>
    </div>
    <div class="content">
      <header>{{ article_data.title }}</header>
      <div class="author-box">
        <img
          class="author-head"
          :src="author_data.authorHead"
          alt=""
          @click="toUserPage(author_data.id)"
        />
        <div class="author-message">
          <div class="author-name">{{ author_data.author }}</div>
          <div class="meta-box">
            {{ article_data.date }} · 浏览量 {{ article_data.viewsNumber }}
          </div>
        </div>
      </div>
      <div class="img-box" v-if="isImg">
        <img :src="article_data.cover_url" alt="" class="img" />
      </div>
      <div class="article-content">
        <mavon-editor
          class="markdown"
          v-model="article_data.articleContent"
          :subfield="false"
          :defaultOpen="'preview'"
          :toolbarsFlag="false"
          :editable="false"
          :boxShadow="false"
          :previewBackground="'#ffffff'"
        ></mavon-editor>
      </div>
      <!-- <hr>   -->
      <div ref="commmentId">
        <Comment
          class="comment"
          :article_id="article_data.id"
          ref="commentChild"
          v-if="article_data.id && isAcitve"
        ></Comment>
      </div>
      <div class="foot"></div>
    </div>
  </div>
</template>
<script>
import { nextTick, onBeforeMount, reactive, ref } from '@vue/runtime-core';
import Comment from '../components/Comment.vue';
import {
  article,
  likeAdd,
  likeDelete,
  collectAdd,
  collectDelete,
  deleteArticle,
} from '@/api/services/article.service';
import { Toast } from 'vant';
import { useRouter } from 'vue-router';
import request from '@/api/request.config.js';
import { userStore } from '@/store/userdata.js';
const useLazyLoad = function () {
  const isAcitve = ref(false);
  // const el = document.getElementById('commmentId');
  const commmentId = ref();
  const lazyLoad = function (el) {
    const clientH = document.documentElement.clientHeight;
    const clientT = document.documentElement.scrollTop;
    if (el.getBoundingClientRect().top < clientH && !isAcitve.value) {
      isAcitve.value = true;
    }
  };
  function throttle(func, wait) {
    var context, args;
    var timer;
    var throttled = function () {
      context = this;
      args = arguments;

      if (!timer) {
        timer = setTimeout(() => {
          timer = null;
          func.apply(context, args);
        }, wait);
      }
    };
    return throttled;
  }
  let throttleLazyLoad = throttle(lazyLoad, 200);
  window.onscroll = () => throttleLazyLoad(commmentId.value);
  return {
    isAcitve,
    commmentId,
  };
};

const user = userStore();
export default {
  name: 'Article',
  components: {
    Comment,
  },
  setup() {
    const router = useRouter();
    let isImg = ref(true);
    const article_data = reactive({
      id: '',
      articleContent: '',
      viewsNumber: '',
      date: '',
      title: '',
      likes: '',
      collections: '',
    });
    const author_data = reactive({
      id: 0,
      author: '',
      authorHead:
        'https://www.pickpik.com/bled-slovenia-lake-mountains-mountain-the-fog-97',
    });
    //点赞按钮
    const good = function () {
      if (article_data.isLiked) {
        article_data.isLiked = false;
        article_data.likes--;
        likeDelete('文章', +router.currentRoute.value.params.id).then((res) => {
          var result = res;
        });
      } else {
        article_data.isLiked = true;
        article_data.likes++;
        likeAdd('文章', +router.currentRoute.value.params.id).then((res) => {
          var result = res;
        });
      }
    };
    let commentChild = ref();
    //评论按钮，这里通过ref来调用comment函数跳转位置
    const comment = function () {
      console.log(isAcitve.value);
      isAcitve.value = true;
      nextTick(() => {
        if (isAcitve.value) {
          commentChild.value.scrollToComment();
        }
      });
    };
    let collectionColor = ref('');
    //收藏按钮
    const collection = function () {
      let id = +router.currentRoute.value.params.id;
      if (article_data.isCollect) {
        collectDelete(id).then((res) => {
          return;
        });
        article_data.isCollect = false;
        article_data.collections--;
      } else {
        collectAdd(id).then((res) => {
          return;
        });
        article_data.isCollect = true;
        article_data.collections++;
      }
      return;
    };
    //获取文章发表时间
    const getTime = function (da) {
      let day = da.slice(0, 10);
      let time = da.slice(11, 16);
      day =
        day.substr(0, 4) +
        '年' +
        day.substr(day.indexOf('-', 0) + 1, 2) +
        '月' +
        day.substr(day.indexOf('-', 6) + 1, 2) +
        '日';
      article_data.date = day + ' ' + time;
    };
    onBeforeMount(() => {
      let targetId = +router.currentRoute.value.params.id;
      article(targetId).then((res) => {
        if (res.message != '获取文章成功！') {
          Toast.fail('文章获取失败');
          return;
        }
        let result = res.result;
        getTime(result.updatedAt);
        article_data.viewsNumber = result.visits;
        article_data.articleContent = result.content;
        article_data.title = result.title;
        article_data.collections = result.collections;
        article_data.likes = result.likes;
        article_data.id = result.id;
        article_data.comments = result.comments;
        article_data.isLiked = result.isLiked;
        article_data.isCollect = result.isCollectioned;
        article_data.cover_url = result.cover_url;
        if (!article_data.cover_url) {
          isImg.value = false;
        }
        request.get(article_data.cover_url).catch((res) => {
          console.log('文件获取失败');
          isImg.value = false;
        });
        author_data.author = result.name;
        author_data.id = result.user_id;
        //头像对接还有问题
        author_data.authorHead = result.avator;
      });
      return;
    });

    //跳转用户资料页面
    const toUserPage = (id) => {
      router.push({
        path: `/others/${id}`,
      });
    };

    //删除文章（仅限自己的）
    const toDeleteArticle = () => {
      deleteArticle(article_data.id)
        .then((res) => {
          Toast('删除文章成功');
          router.push({ path: '/userhome' });
        })
        .catch((rej) => {
          Toast('删除文章失败');
        });
    };
    const { commmentId, isAcitve } = useLazyLoad(commentChild);
    return {
      article_data,
      author_data,
      collectionColor,
      commentChild,
      router,
      isImg,
      isAcitve,
      commmentId,
      good,
      comment,
      collection,
      toUserPage,
      toDeleteArticle,
    };
  },
  computed: {
    //点赞样式
    isLike() {
      return function (article_data) {
        return article_data.isLiked ? 'like-active' : 'like';
      };
    },
    isCollect() {
      return function (article_data) {
        return article_data.isCollect ? 'like-active' : 'like';
      };
    },
    deleteBtnDis() {
      if (this.author_data.id === user.id) {
        return true;
      }
      return false;
    },
  },
};
</script>
<style scoped>
.like {
  color: rgb(156, 158, 161);
}
.like-active {
  color: #1d7dfa;
}
.icon-fanhui {
  font-size: 20px;
}
.v-note-wrapper {
  border: none !important;
}
.init {
  text-align: left;
}
/* 头部样式 */
.header {
  padding: 10px;
  box-shadow: 1px 1px 5px rgb(218, 216, 216);
}
.header-back {
  display: inline-block;
}
.herder-middle {
  display: inline-block;
  position: relative;
  left: 138px;
}
/* 标题样式 */
header {
  font-size: 24px;
  margin: 15px 5px 10px 20px;
  font-weight: 600;
  line-height: 30px;
}
/* 封面样式 */
.img-box {
  padding: 0 25px;
  margin-top: 20px;
}
.img {
  width: 100%;
}
/* 作者信息样式 */
.content {
  margin-top: 8px;
}
.author-head {
  height: 40px;
  widows: 40px;
  margin-right: 12px;
  border-radius: 20px;
}
.author-box {
  display: flex;
  align-items: center;
  margin-left: 20px;
}
.author-name {
  font-size: 16px;
}
.meta-box {
  color: #8a919f;
  font-size: 12px;
}
/* 分割线 */
hr {
  margin: 0 25px;
}
/* 用户评论 */
.comment {
  padding: 20px 25px;
}
/* 评论点赞收藏样式 */
.action-box {
  position: fixed;
  display: flex;
  z-index: 2000;
  bottom: 0;
  width: 375px;
  left: 0;
  height: 45px;
  border-top: 1px solid #ebebeb;
  border-bottom: 1px solid #ebebeb;
  background: #fff;
  /* box-sizing: border-box; */
}
.action {
  display: flex;
  justify-content: center;
  flex: 1 1 50%;
  align-items: center;
  justify-content: center;
  position: relative;
  height: 100%;
  cursor: pointer;
}
.action-img {
  display: flex;
  align-items: center;
  justify-content: center;
}
.action-img-color {
  color: rgb(156, 158, 161);
}
.foot-icon {
  font-size: 20px;
}
.foot-num {
  margin-left: 4px;
  font-size: 14px;
  height: 16px;
  line-height: 16px;
}
.foot {
  height: 20px;
}
.deletBtnDis {
  color: gray;
  border: none;
  background-color: transparent;
  float: right;
}
</style>
